package cn.spike.rockcc.mq.listener;

import cn.spike.rockcc.domain.CourseOrder;
import cn.spike.rockcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

/**
 * @author:spike
 * @create:2023-03-24 10:31
 */
@RocketMQTransactionListener(txProducerGroup = "tx-cancelOrder")
public class OrderCancelListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        if(o == null)return RocketMQLocalTransactionState.ROLLBACK;
        CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(o), CourseOrder.class);
        try {
            courseOrderService.updateOrderAndItems(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        if(message.getPayload()==null) return RocketMQLocalTransactionState.ROLLBACK;
        String orderNo = message.getPayload().toString();
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);
        if(courseOrder.getStatusOrder().equals(CourseOrder.ORDER_TIMEOUT_CANCEL))
            return RocketMQLocalTransactionState.COMMIT;
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
